import { EnumErrorCode } from "../../../../../common/enum/EnumErrorCode";
import { CS_SendHeatBeat, SC_SendHeartBeat } from "../../../../../common/protocols/Proto_SendHeartBeat";
import { Tools } from "../../../../../framework/utils/Tools";
import { Behavior } from "../behavior/Behavior";
import { EnumBehaviorActionType } from "../behavior/EnumBehaviorActionType";
import { EnumBehaviorReturn } from "../behavior/EnumBehaviorReturn";
import { RobotEntity } from "../RobotEntity";
import { EnumBehaviorType } from "./EnumBehaviorType";

export class BehaviorHeartBeat extends Behavior {

    public type: EnumBehaviorType = EnumBehaviorType.HeartBeat;

    public actionType: EnumBehaviorActionType = EnumBehaviorActionType.Sequence;

    public actionState: EnumBehaviorReturn = EnumBehaviorReturn.IDLE

    private lastSendTime: number = 0;
    constructor() {
        super();

    }

    public condition(): boolean {

        const entity: RobotEntity = this.getEntity();
        return entity.isLogined() && (this.actionState != EnumBehaviorReturn.RUNNING) && (Tools.getServerTime() - this.lastSendTime) >= 2;

    }


    public action(): EnumBehaviorReturn {

        this.sendHeartBeat();
        return this.actionState;
    }


    private sendHeartBeat(): void {
        const entity: RobotEntity = this.getEntity();
        const cs: CS_SendHeatBeat = new CS_SendHeatBeat();

        this.actionState = EnumBehaviorReturn.RUNNING;
        this.lastSendTime = Tools.getServerTime();
        entity.sendMsg(cs, (sc: SC_SendHeartBeat) => {
            if (sc.errorcode === EnumErrorCode.OK) {

                this.actionState = EnumBehaviorReturn.SUCCESS;
            }
            
        });


    }

    private register(): void {
    }
}